package com.qf.openapi.web.master.filter;

import com.qf.openapi.web.master.utils.SessionKey;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/logout")
@Slf4j
public class LogoutFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器被初始化");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //1.清空session中的用户登录信息
        HttpSession session = req.getSession();
        session.setAttribute(SessionKey.user_Login_Session_Key, null);
        //2.把用户浏览器本地的cookie删除掉
        Cookie cookie = new Cookie(SessionKey.user_AutoLogin_Cookie_Key, "delete-user-token");
        cookie.setPath("/");
        cookie.setMaxAge(0);//把cookie的有效期设置为0，会然后浏览器马上删除cookie
        resp.addCookie(cookie);
        //如果让请求继续向下传播  filterChain.doFilter();
        //请求就此打住重定向到 login.html
        resp.sendRedirect("/login.html");

    }

    @Override
    public void destroy() {
        System.out.println("过滤器被销毁");
    }
}
